package com.yq.cp.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yq.cp.entity.basics.EquipmentCategory;
import com.yq.cp.entity.basics.EquipmentManagement;
import com.yq.cp.entity.basics.Message;
import com.yq.cp.entity.basics.OrganizationalStructure;
import com.yq.cp.entity.data.NengKongData;
import com.yq.cp.entity.permission.User;
import com.yq.cp.entity.yw.*;
import com.yq.cp.mapper.basics.EquipmentCategoryMapper;
import com.yq.cp.mapper.basics.EquipmentManagementMapper;
import com.yq.cp.mapper.basics.MessageMapper;
import com.yq.cp.mapper.basics.OrganizationalStructureMapper;
import com.yq.cp.mapper.data.NengKongDataMapper;
import com.yq.cp.mapper.yw.YwBjglMapper;
import com.yq.cp.mapper.yw.YwGdxxMapper;
import com.yq.cp.mapper.yw.YwZbglGlryMapper;
import com.yq.cp.service.yw.YwDxfsjlService;
import com.yq.cp.service.yw.YwZbglJjbService;
import com.yq.cp.service.yw.YwZbglXqService;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Configuration
public class Authorization {

    private static String templateCode1="SMS_474110437";//设备故障断链告警
    private static String templateCode2="SMS_474215433";//设备超过阈值短信告警
    @Resource
    OrganizationalStructureMapper organizationalStructureMapper;
    @Resource
    EquipmentManagementMapper equipmentManagementMapper;
    @Resource
    YwDxfsjlService ywDxfsjlService;
    @Resource
    YwZbglXqService ywZbglXqService;
    @Resource
    YwZbglGlryMapper ywZbglGlryMapper;
    @Resource
    NengKongDataMapper nengKongDataMapper;
    @Resource
    YwGdxxMapper ywGdxxMapper;
    @Resource
    YwZbglJjbService ywZbglJjbService;
    @Resource
    YwBjglMapper ywBjglMapper;
    @Resource
    EquipmentCategoryMapper equipmentCategoryMapper;
    @Resource
    MessageMapper messageMapper;


    private static final Logger logger = LoggerFactory.getLogger(Authorization.class);
    @Transactional
    public void query(OrganizationalStructure organizationalStructure) {
        try {
            String key = organizationalStructure.getKeyStr();//"1300386381676718567";
            String keySecret = organizationalStructure.getKeySecret();//"f680e6b5581f4d6bba1e4d00a1045402";
            Map<String,Object> map = new HashMap();
            map.put("pageNo",1);
            map.put("pageSize",10);
           /* map.put("stationId","1298491919448631809");
            map.put("alarmDeviceSn","00FFC0011557001");
            map.put("nmiCode","41028459350");*/
            //map.put("nmiCode","");
            //map.put("sn","120B40198150131");
             /* map.put("stationId","1298491919448631809");
            map.put("nmiCode","41028459350");*/
           /* map.put("id","1308675217944611083");

            map.put("money","元");
            map.put("year","2023");
            //map.put("month","2023-06");
            map.put("timeZone","8");*/
           /* map.put("time","2023-06-27");
            */
            String body = JSON.toJSONString(map);
            String ContentMd5 = getDigest(body);
            String Date = getGMTTime();
            String path = "/v1/api/userStationList";
            String param = "POST" + "\n" + ContentMd5 + "\n" + "application/json" + "\n" + Date + "\n" + path;
            String sign = HmacSHA1Encrypt(param, keySecret);
            //String url = "https://api.ginlong.com:13333/v1/api/inverterDetail";
            String url = organizationalStructure.getUrl()+path;//"https://api.ginlong.com:13333" + path;
            //String url = "https://api.ginlonq.com:13333" + path;
            System.out.println(url);
            //System.out.println(url1);
            OkHttpClient client = new OkHttpClient();

            MediaType xmlType = MediaType.parse("application/json;charset=UTF-8");
            okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(xmlType,body);
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(url)
                    .addHeader("Content-type", "application/json;charset=UTF-8")
                    .addHeader("Authorization","API "+key+":"+sign)
                    .addHeader("Content-MD5",ContentMd5)
                    .addHeader("Date",Date)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            JSONArray jsonArray = JSONObject.parseObject(string).getJSONObject("data").getJSONObject("page").getJSONArray("records");

            logger.info("查询锦浪云：" + string);
            for (int i = 0; i < jsonArray.size(); i++) {
                String sno = JSONObject.parseObject(jsonArray.get(i).toString()).getString("sno");
                BigDecimal power = JSONObject.parseObject(jsonArray.get(i).toString()).getBigDecimal("power");
                if (sno.equals(organizationalStructure.getCode())){
                    this.query3(organizationalStructure,JSONObject.parseObject(jsonArray.get(i).toString()).getString("id"));
                    this.query1(JSONObject.parseObject(jsonArray.get(i).toString()).getString("id"),sno,organizationalStructure);
                }


            }
            System.out.println(string);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public void query3(OrganizationalStructure organizationalStructure,String id) {
        try {
            String key = organizationalStructure.getKeyStr();//"1300386381676718567";
            String keySecret = organizationalStructure.getKeySecret();//"f680e6b5581f4d6bba1e4d00a1045402";
            Map<String,Object> map = new HashMap();
            map.put("id",id);
           /* map.put("stationId","1298491919448631809");
            map.put("alarmDeviceSn","00FFC0011557001");
            map.put("nmiCode","41028459350");*/
            //map.put("nmiCode","");
            //map.put("sn","120B40198150131");
             /* map.put("stationId","1298491919448631809");
            map.put("nmiCode","41028459350");*/
           /* map.put("id","1308675217944611083");

            map.put("money","元");
            map.put("year","2023");
            //map.put("month","2023-06");
            map.put("timeZone","8");*/
            /* map.put("time","2023-06-27");
             */
            String body = JSON.toJSONString(map);
            String ContentMd5 = getDigest(body);
            String Date = getGMTTime();
            String path = "/v1/api/stationDetail";
            String param = "POST" + "\n" + ContentMd5 + "\n" + "application/json" + "\n" + Date + "\n" + path;
            String sign = HmacSHA1Encrypt(param, keySecret);
            //String url = "https://api.ginlong.com:13333/v1/api/inverterDetail";
            String url = organizationalStructure.getUrl()+path;//"https://api.ginlong.com:13333" + path;
            //String url = "https://api.ginlonq.com:13333" + path;
            System.out.println(url);
            //System.out.println(url1);
            OkHttpClient client = new OkHttpClient();

            MediaType xmlType = MediaType.parse("application/json;charset=UTF-8");
            okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(xmlType,body);
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(url)
                    .addHeader("Content-type", "application/json;charset=UTF-8")
                    .addHeader("Authorization","API "+key+":"+sign)
                    .addHeader("Content-MD5",ContentMd5)
                    .addHeader("Date",Date)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            logger.info("查询锦浪云-能源站详情：" + string);
            BigDecimal fullHour = JSONObject.parseObject(string).getJSONObject("data").getBigDecimal("fullHour");
            logger.info("查询锦浪云-能源站详情-等效小时数：" + fullHour);


            NengKongData glData=new NengKongData();
            glData.setName("等效小时数");
            glData.setValue(fullHour);
            glData.setProduceTime(DateTimeUtil.dqsj());
            glData.setEnergyCode(organizationalStructure.getCode());
            glData.setMacCode(null);
            glData.setHourTime(DateTimeUtil.dqsj());
            nengKongDataMapper.insert(glData);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void query1(String id,String s,OrganizationalStructure structure) {
        try {
            String key = structure.getKeyStr();//"1300386381676718567";
            String keySecret = structure.getKeySecret();//"f680e6b5581f4d6bba1e4d00a1045402";
            Map<String,Object> map = new HashMap();
            map.put("pageNo",1);
            map.put("pageSize",10);
            map.put("stationId",id);
           /* map.put("stationId","1298491919448631809");
            map.put("alarmDeviceSn","00FFC0011557001");
            map.put("nmiCode","41028459350");*/
            //map.put("nmiCode","");
            //map.put("sn","120B40198150131");
             /* map.put("stationId","1298491919448631809");
            map.put("nmiCode","41028459350");*/
           /* map.put("id","1308675217944611083");

            map.put("money","元");
            map.put("year","2023");
            //map.put("month","2023-06");
            map.put("timeZone","8");*/
            /* map.put("time","2023-06-27");
             */
            String body = JSON.toJSONString(map);
            String ContentMd5 = getDigest(body);
            String Date = getGMTTime();
            String path = "/v1/api/inverterList";
            String param = "POST" + "\n" + ContentMd5 + "\n" + "application/json" + "\n" + Date + "\n" + path;
            String sign = HmacSHA1Encrypt(param, keySecret);
            //String url = "https://api.ginlong.com:13333/v1/api/inverterDetail";
            String url = structure.getUrl()+path;//"https://api.ginlong.com:13333" + path;
            //String url = "https://api.ginlonq.com:13333" + path;
            System.out.println(url);
            //System.out.println(url1);
            OkHttpClient client = new OkHttpClient();

            MediaType xmlType = MediaType.parse("application/json;charset=UTF-8");
            okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(xmlType,body);
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(url)
                    .addHeader("Content-type", "application/json;charset=UTF-8")
                    .addHeader("Authorization","API "+key+":"+sign)
                    .addHeader("Content-MD5",ContentMd5)
                    .addHeader("Date",Date)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            JSONArray jsonArray = JSONObject.parseObject(string).getJSONObject("data").getJSONObject("page").getJSONArray("records");

            logger.info("查询锦浪云逆变器-能源站：" + structure.getName());
            logger.info("查询锦浪云逆变器：" + string);
            for (int i = 0; i < jsonArray.size(); i++) {
                String sn = JSONObject.parseObject(jsonArray.get(i).toString()).getString("sn");//设备编码
                BigDecimal pac = JSONObject.parseObject(jsonArray.get(i).toString()).getBigDecimal("pac");//功率
                Integer state = JSONObject.parseObject(jsonArray.get(i).toString()).getInteger("state");//逆变器状态：1 = 在线  2 = 离线  3 = 报警

                BigDecimal eTotal = JSONObject.parseObject(jsonArray.get(i).toString()).getBigDecimal("etotal1");//发电量
                logger.info("查询锦浪云逆变器-sn：" + sn);
                logger.info("查询锦浪云逆变器-发电量：" + eTotal);
                logger.info("查询锦浪云逆变器-功率：" + pac);
                xrsj(sn,state,pac,eTotal,i);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void xrsj(String sn,Integer state,BigDecimal pac,BigDecimal eTotal,Integer i) {
        QueryWrapper<EquipmentManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sn", sn);
        queryWrapper.eq("examine", 1);
        EquipmentManagement equipmentManagement = equipmentManagementMapper.selectOne(queryWrapper);
        if (equipmentManagement == null || equipmentManagement.getExamine() == null || equipmentManagement.getExamine() != 1) {
            return;
        }
        OrganizationalStructure organizationalStructure = organizationalStructureMapper.selectById(equipmentManagement.getSiteId());
        if (organizationalStructure == null || organizationalStructure.getExamine() == null || organizationalStructure.getExamine() != 1
                || organizationalStructure.getCode() == null || organizationalStructure.getCode().equals("")) {
            return;
        }
        boolean a = (!Objects.isNull(organizationalStructure.getIsOpen()) && organizationalStructure.getIsOpen() == 1)?true:false;
        //boolean b = (!Objects.isNull(equipmentManagement.getIsOpen()) && equipmentManagement.getIsOpen() == 1)?true:false;
        //if (a || b) {
        if (a) {
            //if (!Objects.isNull(equipmentManagement.getIsOpen()) && equipmentManagement.getIsOpen() == 1){
            if (!Objects.isNull(equipmentManagement.getIsOpen()) && equipmentManagement.getIsOpen() == 0){

            } else if (state!=1){
//                if (false) {
                    QueryWrapper<YwGdxx> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("sb_id", equipmentManagement.getId());
                    queryWrapper1.eq("gdly", 2);
                    queryWrapper1.in("hxzt", 1, 2, 3, 4);
                    boolean exists = ywGdxxMapper.exists(queryWrapper1);
                    if (!exists) {
                        YwZbglJjb ywZbglXq = new YwZbglJjb();
                        ywZbglXq.setSszdId(organizationalStructure.getId());
                        Long cxdqzbxx = ywZbglJjbService.cxdqzbxx(ywZbglXq);

                        YwGdxx ywGdxx = new YwGdxx();
                        ywGdxx.setFzrAuditState(1);
                        ywGdxx.setZzAuditState(1);
                        ywGdxx.setState(1);
                        ywGdxx.setNzzt(0);
                        ywGdxx.setHxzt(1);
                        ywGdxx.setGdly(2);
                        ywGdxx.setWtms("设备离线");
                        ywGdxx.setGdlxId(1L);
                        ywGdxx.setNyzId(organizationalStructure.getId());
                        ywGdxx.setSbbm(sn);
                        ywGdxx.setSbId(equipmentManagement.getId());
                        ywGdxx.setXqId(cxdqzbxx);
                        ywGdxx.setZwslsjTime(DateTimeUtil.laterDateTime(30));
                        ywGdxxMapper.insert(ywGdxx);

                        List<YwZbglGlry> dqzbry = ywZbglJjbService.dqzbry(organizationalStructure.getId());
                        if (dqzbry != null) {
                            for (int j = 0; j < dqzbry.size(); j++) {
                                YwZbglGlry ywZbglGlry = dqzbry.get(j);
                                ywZbglGlry.setId(null);
                                ywZbglGlry.setGlId(ywGdxx.getId());
                                ywZbglGlry.setFl(4);
                                ywZbglGlryMapper.insert(ywZbglGlry);

                                Message message = new Message();
                                message.setUserId(ywZbglGlry.getUserId());
                                message.setTitle("设备离线,请及时处理");
                                message.setType(3);
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }
                        EquipmentCategory equipmentCategory = equipmentCategoryMapper.selectById(equipmentManagement.getEquipmentCategoryId());
                        YwBjgl ywBjgl = new YwBjgl();
                        ywBjgl.setSszdId(organizationalStructure.getId());
                        ywBjgl.setSszdName(organizationalStructure.getName());
                        ywBjgl.setSblx(equipmentCategory.getName());
                        ywBjgl.setBjsb(equipmentManagement.getName());
                        ywBjgl.setBjnr("设备离线");
                        ywBjgl.setBjzt(0);
                        ywBjgl.setGdId(ywGdxx.getId());
                        ywBjgl.setNyzId(organizationalStructure.getId());
                        ywBjglMapper.insert(ywBjgl);


                    }


                }
            //}
        }
        if (state==null || state!=equipmentManagement.getYxzt()){
            equipmentManagementMapper.xgyxzt(equipmentManagement.getId(),state);
        }

        if (pac.compareTo(new BigDecimal(0))==0 ){
            equipmentManagementMapper.xgyxxl(equipmentManagement.getId(),new BigDecimal(0));
        }
        equipmentManagementMapper.xgyxgl(equipmentManagement.getId(),pac);

        String name1="ModBus.逆变器";
        String name2=".有功功率W";
        NengKongData glData=new NengKongData();
        glData.setName(name1+(i+1)+name2);
        glData.setValue(pac);
        glData.setProduceTime(DateTimeUtil.dqsj());
        glData.setEnergyCode(organizationalStructure.getCode());
        glData.setMacCode(equipmentManagement.getSn());
        glData.setHourTime(DateTimeUtil.dqsj());
        nengKongDataMapper.insert(glData);

        if (pac.compareTo(equipmentManagement.getMaximumThreshold())==1 || pac.compareTo(equipmentManagement.getMinimumThreshold())==-1){

            QueryWrapper<YwGdxx> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("sb_id",equipmentManagement.getId());
            queryWrapper1.eq("gdly",3);
            queryWrapper1.in("hxzt",1,2,3,4);
            boolean exists = ywGdxxMapper.exists(queryWrapper1);
//            boolean a = (!Objects.isNull(organizationalStructure.getIsOpen()) && organizationalStructure.getIsOpen() == 1)?true:false;
//            boolean b = (!Objects.isNull(equipmentManagement.getIsOpen()) && equipmentManagement.getIsOpen() == 1)?true:false;
            //if (a || b) {
            if (a) {
            //if (!Objects.isNull(organizationalStructure.getIsOpen()) && organizationalStructure.getIsOpen() == 1) {
                //if (!Objects.isNull(equipmentManagement.getIsOpen()) && equipmentManagement.getIsOpen() == 1) {
                if (!Objects.isNull(equipmentManagement.getIsOpen()) && equipmentManagement.getIsOpen() == 0){

                }else if (!exists){
                    //if (false) {
                        YwZbglJjb ywZbglXq = new YwZbglJjb();
                        ywZbglXq.setSszdId(organizationalStructure.getId());
                        Long cxdqzbxx = ywZbglJjbService.cxdqzbxx(ywZbglXq);
                        YwGdxx ywGdxx = new YwGdxx();
                        ywGdxx.setFzrAuditState(1);
                        ywGdxx.setZzAuditState(1);
                        ywGdxx.setState(1);
                        ywGdxx.setNzzt(0);
                        ywGdxx.setHxzt(1);
                        ywGdxx.setGdly(3);
                        ywGdxx.setWtms("设备超出阈值报警");
                        ywGdxx.setGdlxId(2L);
                        ywGdxx.setNyzId(organizationalStructure.getId());
                        ywGdxx.setSbbm(sn);
                        ywGdxx.setSbId(equipmentManagement.getId());
                        ywGdxx.setXqId(cxdqzbxx);
                        ywGdxx.setZwslsjTime(DateTimeUtil.laterDateTime(30));
                        ywGdxxMapper.insert(ywGdxx);

                        List<YwZbglGlry> dqzbry = ywZbglJjbService.dqzbry(organizationalStructure.getId());
                        if (dqzbry != null) {
                            for (int j = 0; j < dqzbry.size(); j++) {
                                YwZbglGlry ywZbglGlry = dqzbry.get(j);
                                ywZbglGlry.setId(null);
                                ywZbglGlry.setGlId(ywGdxx.getId());
                                ywZbglGlry.setFl(4);
                                ywZbglGlryMapper.insert(ywZbglGlry);


                                Message message = new Message();
                                message.setUserId(ywZbglGlry.getUserId());
                                message.setTitle("设备超出阈值报警,请及时处理");
                                message.setType(3);
                                message.setIsReceive(0);
                                messageMapper.insert(message);
                            }
                        }

                        EquipmentCategory equipmentCategory = equipmentCategoryMapper.selectById(equipmentManagement.getEquipmentCategoryId());
                        YwBjgl ywBjgl = new YwBjgl();
                        ywBjgl.setSszdId(organizationalStructure.getId());
                        ywBjgl.setSszdName(organizationalStructure.getName());
                        ywBjgl.setSblx(equipmentCategory.getName());
                        ywBjgl.setBjsb(equipmentManagement.getName());
                        ywBjgl.setBjnr("设备超出阈值报警");
                        ywBjgl.setBjzt(0);
                        ywBjgl.setGdId(ywGdxx.getId());
                        ywBjgl.setNyzId(organizationalStructure.getId());
                        ywBjglMapper.insert(ywBjgl);
                    }
                //}
            }
        }

//        if (eTotal.compareTo(new BigDecimal(200000))==1){
            name1="ModBus.逆变器";
            name2=".设备发电量01kWh";
            glData=new NengKongData();
            glData.setName(name1+equipmentManagement.getSn()+name2);
            glData.setValue(eTotal);
            glData.setProduceTime(DateTimeUtil.dqsj());
            glData.setEnergyCode(organizationalStructure.getCode());
            glData.setMacCode(equipmentManagement.getSn());
            glData.setHourTime(DateTimeUtil.dqsj());
            nengKongDataMapper.insert(glData);
//        }

    }

    public static void main(String[] args) {

    }
    public static String HmacSHA1Encrypt(String encryptText, String KeySecret) throws Exception
    {
        byte[] data=KeySecret.getBytes("UTF-8");
        SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);

        byte[] text = encryptText.getBytes("UTF-8");
        //瀹屾垚 Mac 鎿嶄綔
        byte[] result = mac.doFinal(text);
        return Base64.encodeBase64String(result);
    }

    public static String  getGMTTime(){

        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //
        String str = sdf.format(cd.getTime());
        return  str;
    }

    public static String getDigest(String test) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(test.getBytes());
            byte[] b = md.digest();
            result = java.util.Base64.getEncoder().encodeToString(b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
}